$(function(){
	var form = $('#auto-exam-form');
	inintIcheck();
	$(document).on('click','.remove-exam',function(){
		var id = $(this).attr('data-id');
		var text = $(this).attr('data-value');
		BootstrapDialog.confirm({
	        title: '确认删除',
	        message:'确定要删除试卷［'+text+'］吗?',
	        
	        callback:function(result){
	            if(result) {
					$.ajax({
						'url':'/biz/exam/destroy/'+id,
				        'type':'DELETE',
				        error: function(data) {
				            layer.open({
				                title: '系统提示',
				                content: '网络异常...'
				            });
				        },
				        success: function(data){
				            if(data.status == 'success'){
				            	$('#item_'+id).remove();
				            	layer.msg(data.msg,{time: 1000});
				            }else{
				                layer.open({
				                    title: '系统提示',
				                    content: data.msg
				                });
				            }
				        }
					});
	            }
	        }
		}).setType(BootstrapDialog.TYPE_DEFAULT);
	});
	
	$(document).on('click','.edit-exam', function(){
		var id = $(this).attr('data-id');
		var container = $('#question-list-container');
		var questionsTemplate = _.template($('#question-list-template').html());
		var text = $(this).attr('data-value');
		$('#question-list').find('.modal-title').text(text);
		$('.loading').show();
		container.html('');
		$.ajax({
			'url':'/biz/exam/questions/'+id,
			'type':'GET',
			'dataType':'json',
			'data':{},
			success: function(data){
				$('.loading').hide();
				var html="";
				$('#question-list').find('.modal-title').text(text+"（"+data.score_count+"分）");
				$.each(data.questions,function(k,v){
            		html += questionsTemplate({item:v});
            	});
				container.html(html);
			}
		});
		
		$('#question-list').modal('show');
	});
	
	$("#add-question").on('change','.question-type',function(){
		var value = parseInt($(this).val());
		switch(value){
		case 0:
			changeQuestion('radio');break;
		case 1:
			changeQuestion('checkbox');break;
		case 2:
			changeQuestion('judge');break;
		case 3:
			changeQuestion('text');break;
		}
	});
	
	$('#checkModel').on('click','.atuo-exam',function () {
		$('#checkModel').modal('hide');
		$('#exam-add-questions').modal('show');
	});
	
	$('#checkModel').on('click','.manual-exam',function () {
		$('#checkModel').modal('hide');
		$('#exam-manual-question').modal('show');
	});
	
	/**
	 * 自动组卷根据题库获取试题
	 */
	$('#exam-add-questions').on('click','.itembank-question-num',function(){
		var container = $('#question-options-container');
		var itemTemplate = _.template($('#question-options-template').html());
		var itembankId = $(this).attr('data-id');
		var disabled = $(this).attr('disabled');
		if(disabled == 'disabled'){
			container.html('<tr><td colspan="2">该题库试题已经被添加过。</td></tr>');
			return false;
		}
		form.find('.auto-questions-add').removeAttr("disabled");
		$('#exam-add-questions').find('.itembank-question-num').removeClass('on');
		$(this).addClass('on');
		$('.loading').show();
		$('#exam-add-questions').find('input[name=itembank]').val(itembankId);
		container.ifEmpty(function(el){
            el.html('<tr><td colspan="2">题库中没有题目，点击<a href="/biz/index">创建</a></td></tr>');
        });
		var params = {
				url: '/biz/question/nums',
				type: 'GET',
				dataType: 'json',
				data: {itembank_id:itembankId},
		};
		$.ajax(params).done(function(resp){
			$('.loading').hide();
			container.html(itemTemplate({item:resp.data}));
		});
		
	});
	/**
	 * 添加试题
	 */
	$('#exam-add-questions').on('click','.auto-questions-add',function(){
		var container = $('#auto-questions-preview-container'); 
		var previewTemplate = _.template($('#auto-questions-template').html());
		var disabled = $(this).attr("disabled");
		if(disabled){
			layer.msg('请选择其它题库继续添加...');
			return false;
		}
		var itembank_id = getFormValue(form,'itembank');
		var data = {
				itembank_id:itembank_id,
				radio_num:getFormValue(form,'radio_num'),
				mulit_num:getFormValue(form,'mulit_num'),
				judge_num:getFormValue(form,'judge_num'),
				discuss_num:getFormValue(form,'discuss_num'),
			}
		var params = {
				url: '/biz/exam/auto-questions',
				type: 'post',
				dataType: 'json',
				data: data,
		};
		$(this).attr("disabled","disabled");
		$.ajax(params).done(function(resp){
			$('#question_num_'+itembank_id).attr('disabled','disabled');
			container.append(previewTemplate({items:resp}));
			container.append('<input type="hidden" name="itembank_id[]" value="'+itembank_id+'">');
			var count = parseInt(form.find('.count_ques').text());
			var radio_num = isNone('radio_num');
			var mulit_num = isNone('mulit_num');
			var judge_num = isNone('judge_num');
			var discuss_num = isNone('discuss_num');
			form.find('.count_ques').text(count+radio_num+mulit_num+judge_num+discuss_num);
			layer.msg('添加成功，你可以点击试卷设置设定分值或选择其它题库继续添加...');
		}).fail(function(erro){
			form.find(".auto-questions-add").removeAttr("disabled");
			error(erro);
		});
	});
	$('#exam-add-questions').on('click','.auto-exam-to-show',function(){
		var preview = $('#auto-questions-preview-container');
		var itembanks = $('#auto-exam-itembank-check');
		var questions = $('#auto-questions-container');
		var modalfooter = $('#auto-modal-footer');
		if(preview.hasClass('hide')){
			$(this).text('试卷选题');
			preview.removeClass('hide');
			itembanks.addClass('hide');
			questions.addClass('hide');
			modalfooter.addClass('hide');
		} else {
			$(this).text('试卷设置');
			preview.addClass('hide');
			itembanks.removeClass('hide');
			questions.removeClass('hide');
			modalfooter.removeClass('hide');
		}
	});
	form.on('click','.auto-destroy',function(){
		var question_count = parseInt(form.find('.count_ques').text());
		var id = $(this).attr('data-id');
		var scoreCount = parseInt(form.find('.count_score').text());
		var score = parseInt(form.find('input[name=score_'+id+']').val());
		if(isNaN(score) || typeof(score) == 'undefined' || score == '') {
			score = 0;
		}
		$(this).parent().parent().remove();
		question_count -= 1;
		form.find('.count_score').text(scoreCount-score)
		form.find('.count_ques').text(question_count);
	});
	form.on('click','.exam-submit',function(){
		var data = form.serializeArray();
		var disabled = $(this).attr("disabled");
		if(disabled){
			return false;
		}
		$(this).attr("disabled","disabled");
		var count_ques = form.find('.count_ques').text();
		var count_score = form.find('.count_score').text();
		if(isEmpty(count_ques)){
			$(this).removeAttr("disabled"); 
			layer.open({
				title:'错误消息',
				content:'请选择题目'
			});
			return false;
		} 
		if(isEmpty(count_score)){
			$(this).removeAttr("disabled"); 
			layer.open({
				title:'错误消息',
				content:'分值不能为空，请选择题目'
			});
			return false;
		} 
		var pass_prop = form.find('input[name=pass_prop]').val();
		if(isEmpty(pass_prop)){
			$(this).removeAttr("disabled"); 
			layer.open({
				title:'错误消息',
				content:'合格比不能为空'
			});
			return false;
		}
		data.push( {
			name:"question_count",
			value:count_ques
		});
		data.push({
				name:"score_count",
				value:count_score
		});
		var params = {
				url: '/biz/exam/munal-create',
				type: 'POST',
				dataType: 'json',
				data:data,
		};
		var container = $('#company-exam-list');
		var listItemTemplate = _.template($('#items-template').html());
		$.ajax(params).done(function(data){
			if(data.status == 'success'){
				form.get(0).reset();
				form.find('.count_ques').text(0);
				form.find('.count_score').text(0)
				$('#auto-questions-preview-container').html('');
				form.find('.auto-questions-add').removeAttr("disabled");
				form.find('.itembank-question-num').removeAttr('disabled');
				form.find('.exam-submit').removeAttr("disabled"); 
				$('#exam-add-questions').modal('hide');
				$('.loading').hide();
				layer.msg(data.msg);
				container.prepend(listItemTemplate({item:data.data}));
			} else {
				form.find('.exam-submit').removeAttr("disabled"); 
				layer.open({title:'提示',content:data.msg});
			}
		}).fail(function(erro){
			form.find('.exam-submit').removeAttr("disabled"); 
			error(erro);
		});
		return false;
	});
	
	form.on('change', saveForm);
	
	function saveForm(){
		var score_count = 0;
		form.find('.count_score').text(0);
		
		form.find('input[name^=score_]').each(function(key,value){
			if(parseInt($(this).val()) > 0){
				score_count += parseInt($(this).val());
			}
		});
		form.find('.count_score').text(score_count);
	}

	function isNone(attr){
		var data = parseInt(form.find('input[name='+attr+']').val());
		var maxNum = parseInt($('#'+attr).text());
		
		if(!isNaN(data) && typeof(data) != 'undefined' && data != '') {
			if(data > maxNum) {
				form.find('input[name='+attr+']').val(maxNum);
				return maxNum;
			}
			return data;
		} else {
			return 0;
		}
	}
});

